package com.yh.zz_hlj.fragment;

import android.content.Intent;
import android.os.Bundle;
import android.support.design.widget.Snackbar;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ExpandableListView;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.yh.zz_hlj.AppConfig;
import com.yh.zz_hlj.AppContext;
import com.yh.zz_hlj.R;
import com.yh.zz_hlj.base.BaseFragment;
import com.yh.zz_hlj.common.CyptoUtils;
import com.yh.zz_hlj.common.PLog;
import com.yh.zz_hlj.common.StringUtils;
import com.yh.zz_hlj.common.Util;
import com.yh.zz_hlj.api.RetrofitSingleton;
import com.yh.zz_hlj.modules.adatper.ExpandableAdapter;
import com.yh.zz_hlj.modules.bean.Result;
import com.yh.zz_hlj.modules.bean.TeamChild;
import com.yh.zz_hlj.modules.bean.TeamGroup;
import com.yh.zz_hlj.modules.bean.User;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import butterknife.ButterKnife;
import butterknife.InjectView;
import rx.Observer;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

/**
 * Created by kangdong on 2016/4/20.
 */
public class TeamFragment extends BaseFragment implements View.OnClickListener {
    @InjectView(R.id.expandableListView)
    ExpandableListView expandableListView;
    ArrayList<TeamGroup> groupDataList = new ArrayList<>();
    List<User> listUser;
    ArrayList<TeamChild> listTeamChild = new ArrayList<TeamChild>();
    ExpandableAdapter adapter;
    String mName;
    int group = 0;
    String type;
    List<String> checkedChildren;

    protected Observer<Result> observer = new Observer<Result>() {
        @Override
        public void onCompleted() {
            PLog.d("s", "onCompleted");
            hideWaitDialog();
        }

        @Override
        public void onError(Throwable e) {
            PLog.d("s", e.getMessage());
            Snackbar.make(expandableListView, e.getMessage(), Snackbar.LENGTH_SHORT).show();
            hideWaitDialog();
        }

        @Override
        public void onNext(Result result) {
            hideWaitDialog();
            if (result != null) {
                int s = result.getStatusCode();
                if (s == 200) {
                    Gson gson = new Gson();
                    Object objects = result.getData();
                    if (objects != null) {
                        String json = gson.toJson(objects);
                        listUser = gson.fromJson(json, new TypeToken<List<User>>() {
                        }.getType());
                        if (listUser != null) {
                            if (listUser.size() > 0) {
                                loadData(listUser);
                            } else {
                                Snackbar.make(expandableListView, "获取数据失败", Snackbar.LENGTH_SHORT).show();
                            }
                        } else {
                            Snackbar.make(expandableListView, "解析出错", Snackbar.LENGTH_SHORT).show();
                        }
                    }
                } else {
                    Snackbar.make(expandableListView, result.getMessage(), Snackbar.LENGTH_SHORT).show();
                }
            }
        }
    };

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        super.onCreateView(inflater, container, savedInstanceState);
        View view = inflater.inflate(R.layout.fragment_team, null);
        ButterKnife.inject(this, view);
        initView(view);
        initData();
        return view;
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            default:
                break;
        }
    }

    @Override
    public void initView(View view) {
        String private_token = AppContext.getInstance().getProperty(AppConfig.PRIVATE_TOKEN);
        String retoken = CyptoUtils.decode(AppConfig.key, private_token);
        showWaitDialog();
        RetrofitSingleton.getApiService(mActivity).
                allWorkers(retoken)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(observer);
        type = getArguments().getString("type");
        if (!StringUtils.isEmpty(type)) {
            setHasOptionsMenu(true);
        }
    }

    @Override
    public void initData() {
        User mUser = AppContext.getInstance().getCurrentUser();
        if (mUser != null) {
            mName = mUser.getDepartmentName() + "-" + mUser.getGXName();
        }
    }

    private void loadData(List<User> listUser) {
        Set<String> nameSet = new HashSet<>();
        for (int i = 0; i < listUser.size(); i++) {
            User scheu = listUser.get(i);
            String departmentName = scheu.getDepartmentName() + "-" + scheu.getGXName();
            nameSet.add(departmentName);
        }
        HashMap<String, ArrayList<User>> scheuHashMaps = new HashMap<String, ArrayList<User>>();
        for (String str : nameSet) {
            ArrayList<User> scheus = new ArrayList<>();
            for (int i = 0; i < listUser.size(); i++) {
                User scheu = listUser.get(i);
                String departmentName = scheu.getDepartmentName() + "-" + scheu.getGXName();
                if (str.equals(departmentName)) {
                    scheus.add(scheu);
                }
            }
            scheuHashMaps.put(str + "", scheus);
        }

        Iterator iter = scheuHashMaps.entrySet().iterator();

        while (iter.hasNext()) {
            Map.Entry entry = (Map.Entry) iter.next();
            String namer = (String) entry.getKey();
            ArrayList<User> mscss = (ArrayList<User>) entry.getValue();

            ArrayList<TeamChild> childList = new ArrayList<TeamChild>();
            for (int i = 0; i < mscss.size(); i++) {
                User mUser = mscss.get(i);
                childList.add(new TeamChild(group + "-" + i, mUser.getUserHead(), mUser.getName(), mUser.getGXName(), "男", mUser.getDepartmentName() + "-" + mUser.getGXName(), mUser.getId()));
            }
            groupDataList.add(new TeamGroup(group + "", namer, childList));
            group++;
        }

        //按名称分组，并把当前班组放到第一个
        Util.sortList(groupDataList, "name", "DESC");
        for (int k = 0; k < groupDataList.size(); k++) {
            String nma = groupDataList.get(k).getName();
            if (nma.equals(mName)) {
                TeamGroup group = groupDataList.get(k);
                groupDataList.remove(k);
                groupDataList.add(0, group);
                k = groupDataList.size();
            }
        }

        adapter = new ExpandableAdapter(getActivity(), groupDataList);
        expandableListView.setAdapter(adapter);
        if (type.equals("select")) {
            adapter.setShowCheckBox(true);
            adapter.setIsClick(false);
        } else {
            adapter.setShowCheckBox(false);
            adapter.setIsClick(true);
        }
        expandableListView.expandGroup(0);
        adapter.notifyDataSetChanged();
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        if (type.equals("select")) {
            int index_menu = R.menu.send_menu;
            inflater.inflate(index_menu, menu);
            menu.getItem(0).setTitle("确定");
        } else {
        }
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.send_btn:
                if (adapter != null) {
                    checkedChildren = adapter.getCheckedChildren();
                    ArrayList<TeamChild> childrens = (ArrayList<TeamChild>) adapter.getCheckedTeamChildren();
                    if (checkedChildren != null) {
                        if (childrens != null) {
                            Intent intent = new Intent(AppConfig.USER_SELECT);
                            Bundle bundle = new Bundle();
                            bundle.putSerializable("checkedChildren", childrens);
                            intent.putExtras(bundle);
                            mActivity.setResult(mActivity.RESULT_OK, intent);
                            mActivity.finish();
                        }
                    } else {
                        Snackbar.make(expandableListView, "未获得您工序员工", Snackbar.LENGTH_SHORT).show();
                    }
                } else {
                    Snackbar.make(expandableListView, "未获得您工序员工", Snackbar.LENGTH_SHORT).show();
                }
                break;
        }
        return true;
    }
}
